import React, { useState, useEffect } from 'react';
import './styles/index.css';

// Components
import ChatHeader from './components/ChatHeader';
import MessageList from './components/MessageList';
import ChatInput from './components/ChatInput';
import Tooltip from './components/Tooltip';
import Sidebar from './components/Sidebar';
import NetworkStatus from './components/NetworkStatus';

// Hooks
import { useChat } from './hooks/useChat';
import { useTooltip } from './hooks/useTooltip';
import { useInput } from './hooks/useInput';
import { useSession } from './hooks/useSession';

// 开发工具
import './utils/apiPathValidator'; // 自动运行API路径验证

const App = () => {
    const [sidebarVisible, setSidebarVisible] = useState(true);
    const [showNetworkStatus, setShowNetworkStatus] = useState(false);

    // 会话管理
    const {
        currentSessionId,
        sessions,
        isLoadingSessions,
        isCreatingSession,
        createNewSession,
        switchSession,
        deleteSession,
        copySession,
        updateSessionTitle,
        isNewlyCreatedSession,
        markSessionAsUsed,
    } = useSession();

    // 聊天功能（使用当前会话ID）
    const { 
        messages, 
        isLoading, 
        isGenerating,
        currentStreamData, 
        sendMessage,
        stopGeneration,
        clearMessages,
        clearMessagesOnly,
        loadHistory,
        loadMoreHistory,
        hasMoreHistory
    } = useChat(currentSessionId);

    // 提示框功能
    const { 
        tooltip, 
        showTooltip, 
        hideTooltip,
        keepTooltip,
        unpinTooltip
    } = useTooltip();

    // 首次发言时为空标题则用用户首条内容命名
    const handleSendWithTitle = async (text) => {
        // 如果是新建会话，标记为已使用
        if (isNewlyCreatedSession(currentSessionId)) {
            markSessionAsUsed(currentSessionId);
        }
        
        await sendMessage(text);
        const current = sessions.find(s => s.id === currentSessionId);
        if (current && (!current.title || current.title.trim() === '' || current.title.trim() === '新对话')) {
            const newTitle = text.slice(0, 20);
            try {
                await updateSessionTitle(currentSessionId, newTitle);
            } catch (e) {
                console.error('更新会话名失败:', e);
            }
        }
    };

    // 输入框功能
    const {
        inputValue,
        setInputValue,
        handleSend,
        handleKeyDown,
        resetInput
    } = useInput(handleSendWithTitle);

    // 监听会话切换，自动加载历史记录
    useEffect(() => {
        if (!currentSessionId) return;
        
        let isCancelled = false; // 用于取消已过期的异步操作
        
        resetInput(); // 清空输入框内容
        
        // 检查是否是新创建的会话
        const isNewSession = isNewlyCreatedSession(currentSessionId);
        console.log('📌 会话切换:', { 
            sessionId: currentSessionId, 
            isNewSession,
            action: isNewSession ? '显示欢迎消息' : '加载历史记录'
        });
        
        if (!isNewSession) {
            // 对于非新建会话，先清空消息然后加载历史记录
            clearMessagesOnly();
            
            // 使用异步函数避免竞态条件
            const loadHistoryAsync = async () => {
                await new Promise(resolve => setTimeout(resolve, 10)); // 极短延迟确保clearMessages生效
                
                // 检查是否已经切换到其他会话
                if (isCancelled) {
                    console.log('⚠️ 会话已切换，取消历史加载:', currentSessionId);
                    return;
                }
                
                console.log('📥 开始加载历史记录:', currentSessionId);
                await loadHistory(currentSessionId);
            };
            
            loadHistoryAsync();
        } else {
            // 新建会话显示欢迎消息
            clearMessages();
        }
        
        // 清理函数：当会话切换时取消之前的异步操作
        return () => {
            isCancelled = true;
            console.log('🔄 会话切换，清理之前的操作');
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [currentSessionId]); // 只依赖currentSessionId，避免不必要的重新执行

    // 处理会话切换
    const handleSwitchSession = (sessionId) => {
        switchSession(sessionId);
        // 由于useEffect会自动处理历史加载，这里不需要手动调用
    };

    // 处理会话删除
    const handleDeleteSession = async (sessionId) => {
        try {
            await deleteSession(sessionId);
            // useEffect会自动处理会话切换后的历史加载
        } catch (error) {
            console.error('删除会话失败:', error);
            throw error;
        }
    };

    // 处理新建会话
    const handleCreateNewSession = async () => {
        try {
            await createNewSession();
            setShowNetworkStatus(false); // 成功后隐藏网络状态
            // useEffect会自动处理新会话的历史加载
        } catch (error) {
            console.error('创建新会话失败:', error);
            if (error.message.includes('Failed to fetch') || error.message.includes('ERR_CONNECTION_REFUSED')) {
                setShowNetworkStatus(true);
            } else {
                alert('创建新会话失败，请重试');
            }
        }
    };

    // 处理网络重试
    const handleNetworkRetry = () => {
        setShowNetworkStatus(false);
        // 重新尝试加载会话列表
        handleCreateNewSession();
    };

    return (
        <div className="app">
            <Sidebar
                sessions={sessions}
                currentSessionId={currentSessionId}
                isLoadingSessions={isLoadingSessions}
                isCreatingSession={isCreatingSession}
                onCreateSession={handleCreateNewSession}
                onSwitchSession={handleSwitchSession}
                onDeleteSession={handleDeleteSession}
                onCopySession={copySession}
                onUpdateSessionTitle={updateSessionTitle}
                isVisible={sidebarVisible}
            />

            <div className="main-content">
                <ChatHeader 
                    onToggleSidebar={() => setSidebarVisible(!sidebarVisible)}
                    currentSessionId={currentSessionId}
                />
                
                {showNetworkStatus && (
                    <NetworkStatus onRetry={handleNetworkRetry} />
                )}
                
                <MessageList
                    messages={messages}
                    isLoading={isLoading}
                    currentStreamData={currentStreamData}
                    onItemHover={showTooltip}
                    onItemLeave={hideTooltip}
                    onLoadMoreHistory={loadMoreHistory}
                    hasMoreHistory={hasMoreHistory}
                />

                <ChatInput
                    inputValue={inputValue}
                    setInputValue={setInputValue}
                    onSend={handleSend}
                    isLoading={isLoading}
                    isGenerating={isGenerating}
                    onStop={stopGeneration}
                    onKeyDown={handleKeyDown}
                    disabled={!currentSessionId || showNetworkStatus}
                />
            </div>

            <Tooltip 
                tooltip={tooltip} 
                onMouseEnter={keepTooltip}
                onMouseLeave={hideTooltip}
                onUnpin={unpinTooltip}
            />
        </div>
    );
};

export default App;